package com.jj.servlet;

import com.alibaba.fastjson2.JSON;
import com.jj.entity.Employee;
import com.jj.entity.Page;
import com.jj.service.EmployeeService;
import com.jj.service.PageService;
import com.jj.service.impl.EmployeeServiceImpl;
import com.jj.service.impl.PageServiceImpl;
import com.jj.util.FileUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.text.SimpleDateFormat;

@WebServlet("/employee")
@MultipartConfig(maxFileSize = 1024 * 1024 * 2) // 2MB
public class EmployeeServlet extends HttpServlet {
    private EmployeeService employeeService = new EmployeeServiceImpl();
    private PageService pageService = new PageServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 允许所有来源访问
        resp.addHeader("Access-Control-Allow-Origin","*");
        // 允许访问的方式
        resp.addHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS");
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        String method = req.getParameter("method")==null?"list":req.getParameter("method");
        switch (method) {
            case "list":
                list(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "edit":
                edit(req, resp);
                break;
            case "update":
                update(req, resp);
                break;
            case "delete":
                delete(req, resp);
                break;
            default:
                break;
        }
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        try {
            Employee employee = new Employee();

            // 处理普通表单字段
            employee.setEmpName(req.getParameter("name"));
            employee.setDeptId(Integer.parseInt(req.getParameter("department")));
            employee.setPosition(req.getParameter("position"));
            employee.setPhone(req.getParameter("phone"));

            // 处理日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            employee.setOnboarding(sdf.parse(req.getParameter("joinDate")));

            // 处理文件上传
            Part filePart = req.getPart("avatar");
            if (filePart != null && filePart.getSize() > 0) {
                String fileName = filePart.getSubmittedFileName();
                // 如果是默认图片，直接使用路径
                if ("default.jpg".equalsIgnoreCase(fileName)) {
                    employee.setImgUrl("img/default.jpg");
                } else {
                    employee.setImgUrl(FileUtil.getImgUrl(req, filePart));
                }
            } else {
                employee.setImgUrl("img/default.jpg");
            }

            boolean result = employeeService.addEmployee(employee);
            resp.getWriter().write(JSON.toJSONString(result));
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write(JSON.toJSONString(false));
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        try {
            Employee employee = new Employee();

            // 必须设置ID才能更新
            employee.setId(Integer.parseInt(req.getParameter("id")));
            employee.setEmpName(req.getParameter("editName"));
            employee.setDeptId(Integer.parseInt(req.getParameter("editDepartment")));
            employee.setPosition(req.getParameter("editPosition")); // 修正参数名
            employee.setPhone(req.getParameter("editPhone"));

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            employee.setOnboarding(sdf.parse(req.getParameter("editJoinDate")));

            Part filePart = req.getPart("editAvatar");
            if (filePart != null && filePart.getSize() > 0) {
                employee.setImgUrl(FileUtil.getImgUrl(req, filePart));
            } else {
                // 保留原有头像
                Employee oldEmp = employeeService.getEmployeeById(employee.getId());
                employee.setImgUrl(oldEmp.getImgUrl());
            }

            boolean result = employeeService.updateEmployee(employee);
            resp.getWriter().write(JSON.toJSONString(result));
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write(JSON.toJSONString(false));
        }
    }

    private void edit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String employeeId = req.getParameter("editModal");
        Employee employee = employeeService.getEmployeeById(Integer.parseInt(employeeId));
        employee.setDeptId(employee.getDepartment().getId());

        // 确保imgUrl有值，如果没有则设置为默认图片
        if(employee.getImgUrl() == null || employee.getImgUrl().isEmpty()) {
            employee.setImgUrl("img/default.jpg");
        }

        String json = JSON.toJSONString(employee,"yyyy-MM-dd");
        resp.getWriter().write(json);
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String employeeId = req.getParameter("employeeId");
        boolean b = employeeService.deleteEmployee(Integer.parseInt(employeeId));
        String json = JSON.toJSONString(b);
        resp.getWriter().write(json);
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageNum = req.getParameter("pageNum");
        String empName = req.getParameter("empName");
        if(pageNum == null || "".equals(pageNum)) {
            pageNum = "1";
        }
        Page<Employee> page = new Page<>();
        page.setPageNum(Integer.parseInt(pageNum));
        page = pageService.findByPage(empName, page);
        String json = JSON.toJSONString(page,"yyyy-MM-dd");
        resp.getWriter().write(json);
    }
}